<?
	layout("/inc/layout.html",{title:"数据加工系统-首页",htmlType:"index",pageName:"home_index"}){
?>


<div id="cl-wrapper" class="fixed-menu">

	<div class="container-fluid" id="pcont">
		<div class="cl-mcont">

			<!-- row start -->
			<div class="row dash-cols">

				<div class="col-sm-6 col-md-6 col-lg-12" align="center" style="margin-top: -20px;">
					<p>
						每日格言：坚强的信心，能使平凡的人做出惊人的事业。——马尔顿
					</p>
					<div style="float: right; margin-top: -25px;">
						<span class="label label-default" id="pack_bar">打包进度显示区</span>
						<button type="button" class="btn btn-success btn-lg" onclick="aKeyToPack();"><i class="fa fa-gavel"></i> 一键打包 </button>
						&nbsp;&nbsp;
						<a href="/package/pack-list.html" type="button" class="btn btn-primary btn" onclick="">已打包列表 </a>
						<p style="color: orangered; font-weight: bold;">提示：打包完成后请到已打包列表下载数据包！</p>
					</div>
				</div>


				<div class="col-sm-6 col-md-6 col-lg-12">


					<div class="tab-container">
						<ul class="nav nav-tabs" id="resources">
							<!--<li class="active"><a href="#home" data-toggle="tab">期刊论文</a></li>
							<li><a href="#profile" data-toggle="tab">新闻资讯</a></li>-->
						</ul>
						<div class="tab-content" id="content">
							<div class="tab-pane active cont" id="home">
								<div class="col-sm-4 col-md-4 col-lg-4" >
									<div class="form-horizontal" role="form">

										<div class="form-group">
											<div class="col-sm-12" style="margin-left: 0px;">
												<button class="btn btn-info" type="button">添加新资源（add）</button>
											</div>
										</div>
									</div>
									<div class="list-group tickets">
										<h4>#数据列表</h4>
										<div id="list">

										</div>
										<div align="center">
											分页: [1] [2] [3] [4] [5]
										</div>
									</div>
								</div>

								<div class="col-sm-8 col-md-8 col-lg-8">
									<div class="form-horizontal" role="form">
										<div class="form-group">
											<div class="col-sm-12" style="margin-left: 80%;">
												<button class="btn btn-info" type="button"> 保存表单 </button>
											</div>
										</div>
										<div id="form">

										</div>
									</div>
								</div>
							</div>
							<div class="tab-pane cont" id="profile">
								<h2>Typography</h2>
								<p>This is just an example of content writen by <b>Jeff Hanneman</b>, as you can see it is a clean design with large
							</div>
						</div>
					</div>
				</div>
			</div>
			<!-- row end -->
		</div>
	</div>
</div>


<?
}
?>

<script type="text/javascript">

var ids = "";
var tempNameEn='';
$(function (){
    showResources();
    //切换标签
   $("#resources").on("click","li",function(){
       deleteRichText(tempNameEn);
       if(tempNameEn != $(this).attr("val")){
           tempNameEn = $(this).attr("val");
	   }
       ids = '';
       showFiels($(this).attr("val"));
       $("#"+$(this).attr("val")).siblings().find("[id$=_form]").html("");
       list(tempNameEn,1);
   });
});
function showResources(){
    $.ajax({
        type : "post",
        url : "/showResources",
        dataType : "json",
        success : function(data) {
			var html = '';
			var html1 = '';
            for(var i = 0; i< data.length;i++){
				if(i == 0){
                    html += '<li class="active" val="'+data[i].nameEn+'"><a href="#tab_'+data[i].nameEn+'" data-toggle="tab">'+data[i].nameZh+'</a></li>';
				}else{
                    html += '<li val="'+data[i].nameEn+'"><a href="#tab_'+data[i].nameEn+'" data-toggle="tab">'+data[i].nameZh+'</a></li>';
				}
				if(i == 0){
                    html1 += '<div class="tab-pane active cont" id="tab_'+data[i].nameEn+'">';
				}else{
                    html1 += '<div class="tab-pane cont" id="tab_'+data[i].nameEn+'">';
				}
				html1 += '<div class="row clear">'
				html1 += '<div class="col-sm-4 col-md-4 col-lg-4">';
				html1 += '<div class="form-horizontal" role="form">';
				html1 += '<div class="form-group">';
				html1 += '<div class="col-sm-12" style="margin-left: 0px;">';
				html1 += '<button class="btn btn-info" type="button" onclick="add();"> 添加新资源（add）  </button>';
				html1 += '</div></div></div>';
				html1 += '<div class="list-group tickets">';
				html1 += '<h4>&nbsp;#数据列表</h4>';
				html1 += '<div id="list">';
				html1 += '</div>';
            	html1 +=  '<div id="page_'+data[i].nameEn+'" style="text-align: center; margin-top: 20px;"></div>'
				html1 += '</div></div>';
				html1 += '<div class="col-sm-8 col-md-8 col-lg-8">';
				html1 += '<div class="form-horizontal" role="form">';
				html1 += '<div class="form-group">';
				html1 += '<div class="col-sm-12" style="text-align: right;">';
				html1 += '<button class="btn btn-info" type="button" onclick="save(\''+data[i].nameEn+'\');"> 保存表单（save） </button>';
				html1 += '</div></div>';
				html1 += '<div id="'+data[i].nameEn+'_form">';
				html1 += '</div></div></div></div></div>';
			}
			$("#resources").html(html);
			$("#content").html(html1);
            showFiels($("#resources").find(".active").attr("val"));
            list($("#resources").find(".active").attr("val"),1);
            tempNameEn=$("#resources").find(".active").attr("val");
        },
        error : function(data) {
            layer.msg("请求失败！", {icon: 2});
        }
    });
}


//拼接表单
function showFiels(nameEn){
    $.ajax({
        type : "post",
        url : "/showFields",
        dataType : "json",
		data:{
			"nameEn":nameEn
		},
        success : function(data) {
            var html = '';
            html += '<input id="resourceNameEn" name="resourceNameEn" type="hidden" class="form-control" value="'+nameEn+'">';
            for(var i = 0; i< data.length;i++){
            	html += '<div class="form-group">';
            	html += '<label class="col-sm-1 control-label">';
				html += data[i].nameZh ;
				html += '</label>';
				html += '<div class="col-sm-11">';
               if(data[i].type == 'img'){
                   html +='<div class="input-group"  style="width: 180px;">';
                   html += '<input id="'+data[i].nameEn+'_1" type="file"/> ';
                   html += '<input id="'+data[i].nameEn+'" name="'+data[i].nameEn+'" type="hidden"/> ';
                   html += '<span class="input-group-btn">';
                   html += '<button class="btn btn-info fa fa-eye preview" type="button" onclick="yulan(this);">  预览</button>';
                   html += '<button class="btn btn-primary fa fa-arrow-up upload" type="button" onclick="shangchuan(this);">  上传</button>';
                   html += ' <button class="btn btn-success fa fa-signal" type="button">  进度：<span class="bar" id="'+data[i].nameEn+'_1_bar">0</span>%</button>';
                   html += '</span>';
                   html += '</div>';
			   }else if(data[i].type == 'file'){
                   html +='<div class="input-group"  style="width: 180px;">';
                   html += '<input id="'+data[i].nameEn+'_1" type="file"/> ';
                   html += '<input id="'+data[i].nameEn+'" name="'+data[i].nameEn+'" type="hidden"/> ';
                   html += '<span class="input-group-btn">';
                   html += '<button class="btn btn-info fa fa-eye preview" type="button" onclick="yulan(this);">  预览</button>';
                   html += '<button class="btn btn-primary fa fa-arrow-up upload" type="button" onclick="shangchuan(this);"> 上传</button>';
                   html += ' <button class="btn btn-success fa fa-signal" type="button">  进度：<span class="bar" id="'+data[i].nameEn+'_1_bar">0</span>%</button>';
                   html += '</span>'
				   html += '</div>';
			   }else if(data[i].type == 'textarea'){
					html += '<textarea class="form-control" style="height: 60px;" id="'+data[i].nameEn+'" name="'+data[i].nameEn+'"></textarea>';
			   }else if(data[i].type == 'select'){
				   html += ' <select id="'+data[i].nameEn+'" name="'+data[i].nameEn+'" class="form-control">';
                   for(var j = 0;j<data[i].value.length;j++){
						html += '<option value="'+data[i].value[j].value+'">'+data[i].value[j].name+'</option>';
				   }
                   html += '</select>';
			   }else if(data[i].type == 'tree'){
					html +='<div class="input-group">';
					html +='<input type="text"  readonly="readonly" class="form-control" id="'+data[i].nameEn+'_1">';
					html +='<input type="hidden" class="form-control" id="'+data[i].nameEn+'" name="'+data[i].nameEn+'">';
				    html += '<span class="input-group-btn">';
                    var v = JSON.stringify(data[i].value).replace(/"/g,"@_@");
					html += '<button class="btn btn-primary" type="button" onclick="dataTree(\''+v+'\',\''+data[i].nameEn+'\',\''+nameEn+'\');">请选择</button>';
                    html += '</span>';
					html += '</div>';
			   }else if(data[i].type == 'richtext'){
               		html += '<script id="'+nameEn+'_'+data[i].nameEn+'" name="'+data[i].nameEn+'" type="text/plain"/>';
				   ids += data[i].nameEn+",";

               }else{
               		html += '<input id="'+data[i].nameEn+'" name="'+data[i].nameEn+'" type="text" class="form-control" placeholder="请输入字符">'
				}
                html += '</div>';
                html += '</div>';
            }
            html = '<form name="'+nameEn+'" id="'+nameEn+'form">' + html + "</form>";
			$("#"+nameEn+"_form").html(html);
            initRichText(nameEn);
        },
        error : function(data) {
            layer.msg("请求失败！", {icon: 2});
        }
    });
}
//销毁富文本
function deleteRichText(nameEn){
    var iids = ids.split(",");
    for(var i = 0;i<iids.length;i++) {
        if (iids[i] != undefined && iids[i] != null && iids[i] != '') {
            console.log(iids[i]);
            UE.getEditor(nameEn + '_' + iids[i]).destroy();
        }
    }
}
//初始化富文本
function initRichText(nameEn) {
	var iids = ids.split(",");
	for(var i = 0;i<iids.length;i++){
		if(iids[i]!=undefined && iids[i]!= null && iids[i] != ''){
            UE.getEditor(nameEn+'_'+iids[i],{ initialFrameHeight:300,initialFrameWidth:'100%' });
		}
	}

}

//-----------------start --弹框---------------------------------
var d;
var id;
var resourceNameEn;
function getData(){
    return d;
}
function getId(){
    return id;
}function getNameEn(){
    return resourceNameEn;
}
//tree弹框
function dataTree(obj,lid,nameEn){
	d = obj;
	id = lid;
    resourceNameEn = nameEn;
    parent.layer.open({
        type : 2,
        icon : 1,
        skin : 'layer-ext-moon',
        area : [ '650px', '650px' ],
        title : "选择分类",
        fix : false, //不固定
        scrollbar : true,
        shadeClose : true,
        //move : true,
        skin : 'layui-layer-rim', //加上边框
        btn : [ '保存 ', '关闭' ],
        content : [ "data-tree.html", 'no' ],
        yes : function(index, layer) {
            //var iframeWin = parent.window[window.name].window[layer.find('iframe')[0]['name']];
            var iframeWin = parent.window[layer.find('iframe')[0]['name']];
            iframeWin.save();
        },
        cancel : function(index) {
        }
    });
}

//保存
function save(nameEn){
    $.ajax({
        cache: true,
        type: "POST",
        url:"/save",
        data: $("#"+nameEn+"form").serialize(),// 你的formid
        async: false,
        success: function(data) {
            layer.msg(data[0].msg);
            list(nameEn,cur);
            add();
        },
		error: function(data) {
        }
    });
}
//新增
function add(){
    var nameen =  $("#resources").find(".active").attr("val");
    deleteRichText(nameen);
    ids = '';
    showFiels(nameen);
}
//-----------------end --弹框---------------------------------
//-----------------start --编辑列表---------------------------------
var cur;
function list(nameEn,curr){
    $.ajax({
        type : "post",
        url : "/editList",
        dataType : "json",
        data:{
            "nameEn":nameEn,
			"page": curr || 1,
        },
        success : function(data) {
            var html = '';
            for(var i=0;i<data.listsize;i++){
				html += '<li class="list-group-item" href="#">';
				html += (i+1)+'. '+data.result[i].nameZh;
				html += '<div style="float: right">';
				html += data.result[i].create_time;
				html += '&nbsp;  <span class="label label-primary" onclick="edit(\''+data.result[i].id+'\')" style="cursor:pointer;">编辑</span>';
				html += '&nbsp; <span class="label label-primary" onclick="editDelete(\''+data.result[i].id+'\')" style="cursor:pointer;">删除</span>';
				html += '</div>';
				html += '</li>';
			}
            $("#tab_"+nameEn).find("#list").html(html);


            laypage({
                cont : document.getElementById('page_'+nameEn), //容器。值支持id名、原生dom对象，jquery对象,
                pages : data.pageSize, //总页数
                skip : false, //是否开启跳页
                skin : 'molv', //加载内置皮肤，也可以直接赋值16进制颜色值，如:#c00
                curr : curr || 1,
                last : data.pageSize,
                groups : 6,//连续显示分页数
                jump : function(obj, first) { //触发分页后的回调
                    if (!first) { //点击跳页触发函数自身，并传递当前页：obj.curr
                        list(nameEn,obj.curr)
                        var curr = obj.curr;
                        cur = obj.curr;
                    }
                }
            });
        },
        error: function(data) {
        }
    });
}
function editDelete(id){
    layer.confirm("是否确认删除？", {
        btn : [ "确定", "取消" ]
        //按钮
    }, function() {
        $.ajax({
            type : "post",
            url : "/editDelete",
            dataType : "json",
            data:{
                "id":id,
                "nameEn":tempNameEn,
            },
            success : function(data) {
                list(tempNameEn,cur);
                layer.msg(data[0].msg);
            },
            error: function(data) {
            }
        });
    }, function() {
    });
}
//数据编辑
function edit(id){
    var className = $("#resources").find(".active").attr("val");
    $.ajax({
        type : "post",
        url : "/edit",
        dataType : "json",
        data:{
            "nameEn":className,
			"id":id
        },
        success : function(data) {
            deleteRichText(className);
            ids = '';
            var html = '';
            html += '<input id="resourceNameEn" name="resourceNameEn" type="hidden" class="form-control" value="'+className+'">';
            html += '<input id="id" name="id" type="hidden" class="form-control" value="'+data[0].data.id+'">';
            for(var i = 0; i< data[0].fields.length;i++){
                html += '<div class="form-group">';
                html += '<label class="col-sm-1 control-label">';
                html += data[0].fields[i].nameZh ;
                html += '</label>';
                html += '<div class="col-sm-11">';
                if(data[0].fields[i].type == 'img'){
                    html +='<div class="input-group"  style="width: 180px;">';
                    html += '<input id="'+data[0].fields[i].nameEn+'_1" type="file" value="'+data[0].data[data[0].fields[i].nameEn]+'"/> ';
                    html += '<input id="'+data[0].fields[i].nameEn+'" name="'+data[0].fields[i].nameEn+'" type="hidden" value="'+data[0].data[data[0].fields[i].nameEn]+'"/> ';
                    html += '<span class="input-group-btn">';
                    html += '<button class="btn btn-sm btn-info fa fa-eye preview" type="button" onclick="yulan(this);">  预览</button>';
                    html += '<button class="btn btn-sm btn-primary fa fa-arrow-up upload" type="button" onclick="shangchuan(this);">  上传</button>';
                    html += ' <button class="btn btn-sm btn-success fa fa-signal" type="button">  进度：<span class="bar" id="'+data[0].fields[i].nameEn+'_1_bar">0</span>%</button>';
                    html += '<button class="btn btn-sm btn-danger fa fa-eye preview" type="button" onclick="edityulan(this);">  下载原上传文件</button>';
                    html += '</span>';
                    html += '</div>';
                }else if(data[0].fields[i].type == 'file'){
                    html +='<div class="input-group"  style="width: 180px;">';
                    html += '<input id="'+data[0].fields[i].nameEn+'_1" type="file" value="'+data[0].data[data[0].fields[i].nameEn]+'"/> ';
                    html += '<input id="'+data[0].fields[i].nameEn+'" name="'+data[0].fields[i].nameEn+'" type="hidden" value="'+data[0].data[data[0].fields[i].nameEn]+'"/> ';
                    html += '<span class="input-group-btn">';
                    html += '<button class="btn btn-sm btn-info fa fa-eye preview" type="button" onclick="yulan(this);">  预览</button>';
                    html += '<button class="btn btn-sm btn-primary fa fa-arrow-up upload" type="button" onclick="shangchuan(this);"> 上传</button>';
                    html += ' <button class="btn btn-sm btn-success fa fa-signal" type="button">  进度：<span class="bar" id="'+data[0].fields[i].nameEn+'_1_bar">0</span>%</button>';
                    html += '<button class="btn btn-sm btn-danger fa fa-eye preview" type="button" onclick="edityulan(this);">  下载原上传文件</button>';
                    html += '</span>';
                    html += '</div>';
                }else if(data[0].fields[i].type == 'textarea'){
                    html += '<textarea class="form-control" style="height: 60px;" id="'+data[0].fields[i].nameEn+'" name="'+data[0].fields[i].nameEn+'" value="'+data[0].data[data[0].fields[i].nameEn]+'">'+data[0].data[data[0].fields[i].nameEn]+'</textarea>';
                }else if(data[0].fields[i].type == 'select'){
                    html += ' <select id="'+data[0].fields[i].nameEn+'" name="'+data[0].fields[i].nameEn+'" class="form-control">';
                    for(var j = 0;j<data[0].fields[i].value.length;j++){
                        if(data[0].data[data[0].fields[i].nameEn] == data[0].fields[i].value[j].value){
                            html += '<option value="'+data[0].fields[i].value[j].value+'" selected="selected">'+data[0].fields[i].value[j].name+'</option>';
						}else{
                            html += '<option value="'+data[0].fields[i].value[j].value+'">'+data[0].fields[i].value[j].name+'</option>';
						}
                    }
                    html += '</select>';
                }else if(data[0].fields[i].type == 'tree'){
                    html +='<div class="input-group">';
                    var ff=false;
                    for(var j = 0;j<data[0].fields[i].value.length;j++){
                        if(data[0].data[data[0].fields[i].nameEn] == data[0].fields[i].value[j].value){
                            html +='<input type="text" readonly="readonly" class="form-control" id="'+data[0].fields[i].nameEn+'_1" value="'+data[0].fields[i].value[j].name+'">';
							ff = true;
                        }
					}
					if(!ff){
                        html +='<input type="text" class="form-control" id="'+data[0].fields[i].nameEn+'_1" value="">';
					}
                    html +='<input type="hidden" class="form-control" id="'+data[0].fields[i].nameEn+'" name="'+data[0].fields[i].nameEn+'" value="'+data[0].data[data[0].fields[i].nameEn]+'">'
                    html += '<span class="input-group-btn">';
                    var v = JSON.stringify(data[0].fields[i].value).replace(/"/g,"@_@");
                    html += '<button class="btn btn-primary" type="button" onclick="dataTree(\''+v+'\',\''+data[0].fields[i].nameEn+'\',\''+className+'\');">请选择</button>';
                    html += '</span>';
                    html += '</div>';
                }else if(data[0].fields[i].type == 'richtext'){
                    html += '<script id="'+className+'_'+data[0].fields[i].nameEn+'" name="'+data[0].fields[i].nameEn+'" type="text/plain">'+data[0].data[data[0].fields[i].nameEn]+"<"+"/script>";
                    ids += data[0].fields[i].nameEn+",";

                }else{
                    html += '<input id="'+data[0].fields[i].nameEn+'" name="'+data[0].fields[i].nameEn+'" type="text" class="form-control" placeholder="请输入字符" value="'+data[0].data[data[0].fields[i].nameEn]+'">'
                }
                html += '</div>';
                html += '</div>';
            }
            html = '<form name="'+className+'" id="'+className+'form">' + html + "</form>";
            $("#"+className+"_form").html(html);

            initRichText(className);
		},
        error : function(data) {
            layer.msg("请求失败！", {icon: 2});
        }
    });
}
//-----------------end --编辑列表---------------------------------

//----------------start--一键打包----------------------------------
function aKeyToPack(){
    layer.confirm("是否要一键打包？", {
        btn : [ "确定", "取消" ]
        //按钮
    }, function() {
        $.ajax({
            type : "post",
            url : "/aKeyToPack",
            dataType : "json",
            success : function(data) {
                list(tempNameEn,cur);
                layer.msg(data[0].msg);
                packBar();
            },
            error: function(data) {
            }
        });
    }, function() {
    });
}

//----------------end--一键打包----------------------------------
//========================== 打包进度==============================================

function packBar(){
    $.ajax({
        type : "post",
        url : "/packBar",
        dataType : "json",
        async:true,
        success : function(data) {
            if(data[0].msg==''){
                setTimeout("packBar()", 1000);
            }else{
                $("#pack_bar").html(data[0].msg);
                if(data[0].status == '0'){
                    setTimeout("packBar()", 1000);
                }
            }
        },
        error: function(data) {
        }
    });

}
//========================== 打包进度==============================================
//**********************start 文件上传*******************************************
function yulan(obj){
    console.log($(obj).parent().siblings("input")[0].files);
    window.open(URL.createObjectURL($(obj).parent().siblings("input")[0].files[0]));
}
function edityulan(obj){
    console.log($(obj).parent().siblings("input").eq(1).val());
    window.location.href='/reading?path='+$(obj).parent().siblings("input").eq(1).val();
}
//上传
function shangchuan(obj){
    if($(obj).parent().siblings("input").eq(0).val() == ''){
        layer.msg("请添加选择文件", {icon: 2});
        return;
    }else{
        uploadFunction($(obj).parent().siblings("input").eq(0).attr("id"));
    }
}

//文件上传
function uploadFunction(nameEn) {
    var nn = $("#resources").find(".active").attr("val");
    var uploadFile = $("#"+nn+"form #"+nameEn).get(0).files[0]; //获取文件对象
    // FormData 对象
    var form = new FormData();
    form.append("file", uploadFile); // 文件对象
    $.ajax({
        cache : false,
        type : "POST",
        url : "/fileUpload",
        contentType : false,
        //contentType设置为false。因为是由<form>表单构造的FormData对象，且已经声明了属性enctype="multipart/form-data"
        //如果不是用<form>表单构造FormData对象,append()的第二个参数应是文件对象，即$('#file')[0].files[0],contentType也要设置为‘false’。
        processData : false,//processData设置为false。因为data值是FormData对象，不需要对数据做处理
        data : form,
        xhr : function() { //获取ajaxSettings中的xhr对象，为它的upload属性绑定progress事件的处理函数
            myXhr = $.ajaxSettings.xhr();
            if (progressFunction && myXhr.upload) { //检查进度函数和upload属性是否存在
                //绑定progress事件的回调函数
                myXhr.upload.addEventListener("progress",
                    function(evt){
                        if (evt.lengthComputable) {//lengthComputable，表示进度信息是否可用的布尔值；target，对应的 XHR 对象；
                            var completePercent = Math.round(evt.loaded / evt.total*100);//loaded:已经接收的字节数；,total:响应数据的预期总字节数，根据 Content-Length 响应头部确定
                            $("#"+nn+"form #"+nameEn+"_bar").text(completePercent);
                        }
                    }, true);
            }
            return myXhr; //xhr对象返回给jQuery使用
        },
        error : function(request) {
            layer.msg("请求失败！", {icon: 2});
        },
        success : function(data) {
            //$("#btnUpload").val("上传完成");
            var jsonO = eval(data);
            if(jsonO[0].info =="error"){
                layer.msg("上传失败!");
            }else{
                $("#"+nn+"form #"+nameEn.split("_")[0]).val(jsonO[0].info);
                $("#"+nn+"form #" +nameEn+"_bar").text("100");
            }
        }
    });
}
//进度条控制
function progressFunction(evt) {
    if (evt.lengthComputable) {//lengthComputable，表示进度信息是否可用的布尔值；target，对应的 XHR 对象；
        var completePercent = Math.round(evt.loaded / evt.total*100);//loaded:已经接收的字节数；,total:响应数据的预期总字节数，根据 Content-Length 响应头部确定
        $("#"+nameEn+"_bar").text(completePercent);
    }
}
//**********************end 文件上传*******************************************
</script>